package com.iot.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.iot.commons.ResponseResult;
import com.iot.enums.StatusEnum;
import com.iot.mapper.ElectronicFenceMapper;
import com.iot.model.entity.ElectronicFenceEntity;
import com.iot.model.query.ElectronicFenceQuery;
import com.iot.model.dto.ElectronicFenceDto;
import com.iot.model.vo.AuthInfoVo;
import com.iot.model.vo.ElectronicFenceVo;
import com.iot.service.ElectronicFenceService;
import com.iot.utils.DateUtil;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import com.iot.utils.ResponseResultUtil;

import java.util.List;

/**
 * ElectronicFenceServiceImpl
 *
 * @author: dh
 * @date: 2024-04-21 12:17:00
 */
@Service
@RequiredArgsConstructor
public class ElectronicFenceServiceImpl implements ElectronicFenceService {

    private final ElectronicFenceMapper electronicFenceMapper;

    @Override
    public ResponseResult getList(ElectronicFenceQuery electronicFence) {
        AuthInfoVo authInfoEntity = (AuthInfoVo) StpUtil.getSession().get("loginInfo");
        if (null == authInfoEntity) {
            return ResponseResultUtil.authInfoFailure();
        }
        Page<ElectronicFenceEntity> page = new Page<>(electronicFence.getPageIndex(), electronicFence.getPageSize());
        LambdaQueryWrapper<ElectronicFenceEntity> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(ElectronicFenceEntity::getState, StatusEnum.VALID.getKey());
        queryWrapper.eq(ElectronicFenceEntity::getAuthId, authInfoEntity.getId());
        queryWrapper.orderByDesc(ElectronicFenceEntity::getCreateTime);
        IPage<ElectronicFenceEntity> electronicFencePage = electronicFenceMapper.selectPage(page, queryWrapper);
        List<ElectronicFenceVo> electronicFenceVoList = Lists.newArrayList();
        for (ElectronicFenceEntity electronicFenceEntity : electronicFencePage.getRecords()) {
            ElectronicFenceVo vo = new ElectronicFenceVo();
            vo.setId(electronicFenceEntity.getId());
            vo.setName(electronicFenceEntity.getName());
            vo.setLon(electronicFenceEntity.getLon());
            vo.setLat(electronicFenceEntity.getLat());
            vo.setIsEffect(electronicFenceEntity.getIsEffect());
            vo.setRadius(electronicFenceEntity.getRadius());
            electronicFenceVoList.add(vo);
        }

        return ResponseResultUtil.success(electronicFencePage.getTotal(), electronicFenceVoList);
    }

    @Override
    public ResponseResult edit(ElectronicFenceDto electronicFence) {
        if (null == electronicFence || null == electronicFence.getId()) {
            return ResponseResultUtil.paramFailure();
        }
        ElectronicFenceEntity entity = new ElectronicFenceEntity();
        entity.setId(electronicFence.getId());
        entity.setAuthId(electronicFence.getAuthId());
        entity.setName(electronicFence.getName());
        entity.setLon(electronicFence.getLon());
        entity.setLat(electronicFence.getLat());
        entity.setRadius(electronicFence.getRadius());
        electronicFenceMapper.updateById(entity);
        return ResponseResultUtil.success();
    }


    @Override
    public ResponseResult effect(ElectronicFenceDto electronicFence) {
        AuthInfoVo authInfoEntity = (AuthInfoVo) StpUtil.getSession().get("loginInfo");
        if (null == authInfoEntity) {
            return ResponseResultUtil.authInfoFailure();
        }
        if (null == electronicFence ) {
            return ResponseResultUtil.paramFailure();
        }
        Long id = electronicFence.getId();
        Integer isEffect = electronicFence.getIsEffect();
        if (null == electronicFence.getId() || null == isEffect) {
            return ResponseResultUtil.paramFailure();
        }

        if (isEffect.equals(1)) {
            clean(authInfoEntity.getId());
        }
        ElectronicFenceEntity entity = new ElectronicFenceEntity();
        entity.setId(id);
        entity.setIsEffect(isEffect);
        electronicFenceMapper.updateById(entity);
        return ResponseResultUtil.success();
    }

    private void clean(Long authId){
        LambdaUpdateWrapper<ElectronicFenceEntity> updateWrapper = Wrappers.lambdaUpdate();
        updateWrapper.eq(ElectronicFenceEntity::getAuthId, authId);
        updateWrapper.eq(ElectronicFenceEntity::getState,StatusEnum.VALID.getKey());
        ElectronicFenceEntity entity = new ElectronicFenceEntity();
        entity.setIsEffect(0);
        electronicFenceMapper.update(entity,updateWrapper);
    }


    @Override
    public ResponseResult delete(ElectronicFenceDto electronicFence) {
        if (null == electronicFence || null == electronicFence.getId()) {
            return ResponseResultUtil.paramFailure();
        }
        ElectronicFenceEntity entity = new ElectronicFenceEntity();
        entity.setId(electronicFence.getId());
        entity.setState(StatusEnum.DELETE.getKey());
        electronicFenceMapper.updateById(entity);
        return ResponseResultUtil.success();
    }

    @Override
    public ResponseResult add(ElectronicFenceDto electronicFence) {
        if (null == electronicFence) {
            return ResponseResultUtil.paramFailure();
        }
        if (StringUtils.isEmpty(electronicFence.getName()) || StringUtils.isEmpty(electronicFence.getLon())
                || StringUtils.isEmpty(electronicFence.getLat()) || null == electronicFence.getRadius()) {
            return ResponseResultUtil.paramFailure();
        }
        AuthInfoVo authInfoEntity = (AuthInfoVo) StpUtil.getSession().get("loginInfo");
        if (null == authInfoEntity) {
            return ResponseResultUtil.authInfoFailure();
        }
        Long authId = authInfoEntity.getId();
        LambdaQueryWrapper<ElectronicFenceEntity> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(ElectronicFenceEntity::getState, StatusEnum.VALID.getKey());
        queryWrapper.eq(ElectronicFenceEntity::getAuthId, authId);
        Long count = electronicFenceMapper.selectCount(queryWrapper);
        if (count >= 20) {
            return ResponseResultUtil.failure("电子围栏数量不能超过5个");
        }

        ElectronicFenceEntity entity = new ElectronicFenceEntity();
        entity.setAuthId(authId);
        entity.setName(electronicFence.getName());
        entity.setLon(electronicFence.getLon());
        entity.setLat(electronicFence.getLat());
        entity.setRadius(electronicFence.getRadius());
        Integer isEffect = electronicFence.getIsEffect();
        if (null == isEffect) {
            entity.setIsEffect(0);
        }else {
            if (isEffect.equals(1)) {
                clean(authInfoEntity.getId());
            }
            entity.setIsEffect(isEffect);
        }
        entity.setState(StatusEnum.VALID.getKey());
        entity.setCreateTime(DateUtil.now());
        electronicFenceMapper.insert(entity);
        return ResponseResultUtil.success();
    }

    @Override
    public ResponseResult getById(ElectronicFenceQuery electronicFence) {
        ElectronicFenceEntity electronicFenceEntity = electronicFenceMapper.selectById(electronicFence.getId());
        ElectronicFenceVo vo = new ElectronicFenceVo();
        vo.setId(electronicFenceEntity.getId());
        vo.setName(electronicFenceEntity.getName());
        vo.setLon(electronicFenceEntity.getLon());
        vo.setLat(electronicFenceEntity.getLat());
        vo.setRadius(electronicFenceEntity.getRadius());
        return ResponseResultUtil.success(vo);
    }

    @Override
    public List<ElectronicFenceEntity> getByIds(List<Long> ids) {
        if (CollectionUtils.isEmpty(ids)) {
            return null;
        }
        LambdaQueryWrapper<ElectronicFenceEntity> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(ElectronicFenceEntity::getState, StatusEnum.VALID.getKey());
        queryWrapper.in(ElectronicFenceEntity::getId, ids);
        queryWrapper.orderByDesc(ElectronicFenceEntity::getCreateTime);
        return electronicFenceMapper.selectList(queryWrapper);
    }
}
